package com.jds.test.consoleim;

import io.netty.channel.*;

/**
 * Created by sunyuming on 18/8/1.
 */
public class ClientHandler4 extends SimpleChannelInboundHandler<BaseBean> {

    public int type;
    public String to;
    public Channel channel;

    public void send(String line) {
        BaseBean baseBean = new BaseBean();
        baseBean.setType(type);
        baseBean.setText(to);
        baseBean.setText(line);
        ChannelFuture channelFuture = channel.writeAndFlush(baseBean);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                type = 1;
            }
        });
    }

    //接受服务端发来的消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseBean msg) throws Exception {
        System.out.println(msg.getText());
    }

    //与服务器建立连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channel = ctx.channel();
        System.out.println("已连接服务器，请输入 -l xxxx 登陆，设定昵称\n");
    }

    //与服务器断开连接
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("成功退出");
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭管道
        ctx.channel().close();
        //打印异常信息
        cause.printStackTrace();
    }

}
